<template>
  <div>
    <el-row :gutter="6" style="padding: 10px">
      <el-col :span="5" style="margin-left: 10px">
        <el-card class="box-card">
          <template #header>
            <!--            class="card-header"-->
            <div>
              <el-row class="flex justify-start">
                <div class="text">年级列表</div>
              </el-row>
              <el-row class="mt-10px">
                <div>
                  <el-input
                    v-model="gradeQuery.name"
                    placeholder="请输入年级名称"
                    clearable
                    size="small"
                    @keyup.enter="handleGradeFilter"
                    @clear="handleGradeFilter"
                    class="w-120px!"
                  />
                  <el-button
                    type="primary"
                    size="small"
                    icon="Search"
                    @click="handleGradeFilter"
                  >
                    筛选
                  </el-button>
                </div>
              </el-row>
            </div>
          </template>
          <el-table
            row-class-name="table-row-selectable"
            v-loading="ageLoading"
            highlight-current-row
            :data="gradeList"
            style="height: 75vh"
            @row-click="handleGradeClick"
          >
            <el-table-column prop="name" label="年级名称" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="17">
        <el-card class="box-card">
          <template #header>
            <div>
              <el-row class="flex justify-between">
                <div class="text">核心课程列表</div>
                <div v-if="currentGradeId !== ''">
                  <el-button
                    type="primary"
                    icon="Check"
                    @click="handleSaveOrderNum"
                    size="small"
                  >
                    保存排序
                  </el-button>
                  <el-button icon="Refresh" @click="handleReset" size="small">
                    重置
                  </el-button>
                </div>
              </el-row>
              <el-row class="mt-10px">
                <el-button
                  type="primary"
                  @click="handleAddCourseToGradeDialog"
                  size="small"
                  :disabled="currentGradeId === ''"
                >
                  <template #icon>
                    <icon-ic-baseline-add-circle-outline />
                  </template>
                  添加课程
                </el-button>
                <el-button
                  type="danger"
                  @click="handleRemoveCoursesFromGrade()"
                  size="small"
                  :disabled="multiple"
                >
                  <template #icon>
                    <icon-ic-baseline-remove-circle-outline />
                  </template>
                  移出课程
                </el-button>
              </el-row>
            </div>
          </template>
          <el-table
            v-loading="coreCourseLoading"
            :data="coreCourseList"
            ref="coreCourseTableRef"
            style="height: 75vh"
            @selection-change="handleSelectionChange"
            :default-sort="{ prop: 'coreOrderNum', order: 'descending' }"
          >
            <!--            @select="handleSelectionChange"-->
            <!--            @select-all="handleSelectAll"-->
            <el-table-column type="selection" width="30" align="center" />
            <el-table-column prop="coreOrderNum" label="顺序号" width="80" />
            <el-table-column prop="name" label="课程名称" />
            <el-table-column prop="userName" label="创建者" width="120" />
            <el-table-column prop="sceneName" label="场景" width="120" />
            <el-table-column prop="totalSection" label="章节数" width="80" />
            <el-table-column
              prop="organizationName"
              label="所属机构"
              width="120"
            />
            <!-- <el-table-column prop="key" label="角色key" /> -->
            <el-table-column
              label="操作"
              align="left"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <span>
                  <el-tooltip content="移出" :enterable="false" placement="top">
                    <el-button
                      link
                      type="primary"
                      @click="handleRemoveCoursesFromGrade(scope.row)"
                    >
                      <template #icon>
                        <icon-ic-baseline-remove-circle-outline />
                      </template>
                    </el-button>
                  </el-tooltip>
                </span>
                <span v-if="scope.$index !== 0" class="pl-10px">
                  <el-tooltip content="上移" placement="top" :enterable="false">
                    <el-button
                      link
                      type="primary"
                      icon="ArrowUp"
                      @click="handleMoveCourseUp(scope.$index, scope.row)"
                    ></el-button>
                  </el-tooltip>
                </span>
                <span
                  v-if="scope.$index !== coreCourseList.length - 1"
                  class="pl-10px"
                >
                  <el-tooltip content="下移" placement="top" :enterable="false">
                    <el-button
                      link
                      type="primary"
                      icon="ArrowDown"
                      @click="handleMoveCourseDown(scope.$index, scope.row)"
                    ></el-button>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程列表对话框 -->
    <el-dialog
      v-model="dialogStatus.isShow"
      :title="dialogStatus.title"
      width="80%"
      center
      :close-on-click-modal="false"
      default-sort="createTime"
      @close="handleCloseDialog"
    >
      <template #header="{ titleClass, titleId }">
        <el-row justify="center" align="middle" class="mb-2">
          <el-col :span="24">
            <div :id="titleId" :class="titleClass">
              {{ dialogStatus.title }}
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="flex justify-between">
          <div>
            <el-button
              type="primary"
              plain
              :disabled="dialogStatus.multiple"
              @click="handleAddCourseToGrade()"
            >
              <template #icon>
                <icon-ic-baseline-add-circle-outline />
              </template>
              添加
            </el-button>
          </div>

          <div>
            <el-input
              v-model="unbindCourseQuery.name"
              placeholder="请输入课程名称"
              clearable
              class="w-200px!"
            />
            <el-button
              type="primary"
              icon="Search"
              @click="getUnbindCourseList"
              v-hasPermi="['system:user:add']"
              class="ml-12px"
            >
              搜索
            </el-button>

            <!--            <right-toolbar-->
            <!--              v-model:showSearch="showSearch"-->
            <!--              :search="false"-->
            <!--              @queryTable="getUnbindCourseList"-->
            <!--            >-->
            <!--            </right-toolbar>-->
          </div>
        </el-row>
      </template>
      <el-table
        highlight-current-row
        style="width: 100%"
        ref="roleTable"
        :data="dialogData.courseList"
        @selection-change="handleDialogSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column prop="name" label="课程名称" width="240" />
        <el-table-column prop="userName" label="创建者" width="120" />
        <el-table-column prop="sceneName" label="场景" width="120" />
        <el-table-column prop="totalSection" label="章节数" width="80" />
        <el-table-column prop="organizationName" label="所属机构" width="120" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="160"
          sortable
        />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span class="pl-5" v-hasPermi="['system:user:edit']">
              <el-tooltip content="添加" :enterable="false" placement="top">
                <el-button
                  link
                  type="primary"
                  @click="handleAddCourseToGrade(scope.row)"
                >
                  <template #icon>
                    <icon-ic-baseline-add-circle-outline />
                  </template>
                </el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <template #footer>
        <pagination
          v-show="dialogData.total > 0"
          :total="dialogData.total"
          :page-sizes="[5, 10, 15, 20]"
          v-model:page="unbindCourseQuery.pageNum"
          v-model:limit="unbindCourseQuery.pageSize"
          @pagination="getUnbindCourseList"
        />
        <!--      :pager-count="3"-->
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getGradeList as getGradeListApi,
  getCourseList as getCourseListApi,
  addCoursesToGrade as addCoursesToGradeApi,
  removeCoursesFromGrade as removeCoursesFromGradeApi,
  saveCoreCourseOrder as saveCoreCourseOrderApi,
} from "@/service/api/course/core";
import to from "await-to-js";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import {
  CourseCourseVo,
  CourseGradeVo,
} from "@/service/api/course/core/types.ts";
import Pagination from "@/components/Pagination/index.vue";
import { CourseLabelVo } from "@/service/api/course/tag/types.ts";
import { ElButton, ElTable } from "element-plus";

const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);

const coreCourseTableRef = ref<InstanceType<typeof ElTable>>();

const ageLoading = ref(false);
const coreCourseLoading = ref(false);

const roleTable = ref();

const initGradeQuery = {
  name: "",
};

const initCoreCourseQuery = {
  gradeId: "",
  orderByColumn: "coreOrderNum",
  orderType: "asc",
};

const initUnbindCourseQuery = {
  name: undefined,
  core: false,
  onlineStatus: "2",
  pageNum: 1,
  pageSize: 10,
  orderByColumn: "createTime",
  orderType: "desc",
};

const initDialogStatus = {
  isShow: false,
  title: "",
  ids: <string[]>[],
  selection: <CourseCourseVo[]>[],
  single: true,
  multiple: true,
};

const initDialogData = {
  courseList: <CourseCourseVo[]>[],
  total: 0,
};

const data = reactive({
  gradeList: <CourseGradeVo[]>[],
  coreCourseList: <CourseCourseVo[]>[],
  // 获取年级参数
  gradeQuery: {
    ...initGradeQuery,
  },
  // 获取核心课程参数
  coreCourseQuery: {
    ...initCoreCourseQuery,
  },
  unbindCourseQuery: {
    ...initUnbindCourseQuery,
  },
  dialogStatus: {
    ...initDialogStatus,
  },
  dialogData: {
    ...initDialogData,
  },
  // 用户绑定角色时的参数
  // queryParams: {
  //   ...initQueryParams,
  // },
});

const {
  gradeList,
  coreCourseList,
  gradeQuery,
  coreCourseQuery,
  unbindCourseQuery,
  dialogStatus,
  dialogData,
} = toRefs(data);

const currentGradeId = ref<string>("");

/**
 * 获取孩子年级列表
 */
const getGradeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<CourseGradeVo>, any>(
    getGradeListApi(gradeQuery.value),
  );

  if (!err) {
    gradeList.value = res?.rows ?? [];
    return true;
  }
  return false;
};

/**
 * 对课程进行排序
 */
const sortCoreCourse = () => {
  coreCourseTableRef.value?.sort("coreOrderNum", "ascending");
};

// 设置状态
// const statusType = (status: string) => {
//   switch (status) {
//     case "正常":
//       return "success";
//     case "未确认":
//       return "warning";
//     case "禁言":
//       return "danger";
//     case "停用":
//       return "info";
//     default:
//       return "";
//   }
// };

/**
 * 处理用户列表被点击
 * @param row
 */
const handleGradeClick = async (row: any) => {
  coreCourseLoading.value = true;
  // queryParams.value.userId = row.id;
  coreCourseQuery.value.gradeId = row.id;
  currentGradeId.value = row.id;
  await getCoreCourseList();
  coreCourseLoading.value = false;
};

/**
 * 获取核心课程列表
 */
const getCoreCourseList = async (): Promise<boolean> => {
  coreCourseLoading.value = true;
  const [err, res] = await to<BasePageResponse<CourseCourseVo>, any>(
    getCourseListApi(coreCourseQuery.value),
  );
  if (!err) {
    coreCourseList.value = res?.rows ?? [];
    coreCourseList.value.forEach((item, index) => {
      item.coreOrderNum = index + 1;
    });
    coreCourseLoading.value = false;
    return true;
  }

  coreCourseLoading.value = false;
  return false;
};

/**
 * 获取未绑定年级的课程列表
 */
const getUnbindCourseList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<CourseCourseVo>, any>(
    getCourseListApi(unbindCourseQuery.value),
  );
  if (!err) {
    dialogData.value.courseList = res?.rows ?? [];
    dialogData.value.total = Number(res?.total ?? 0);
    return true;
  }
  return false;
};

/**
 * 添加课程到年级弹出对话框
 */
const handleAddCourseToGradeDialog = async () => {
  const response = await getUnbindCourseList();

  if (response) {
    dialogStatus.value.title = "添加课程到年级";
    dialogStatus.value.isShow = true;
  }
};

/**
 * 添加课程到年级
 * @param row
 */
const handleAddCourseToGrade = async (row?: CourseCourseVo) => {
  // 询问是否添加
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定添加该课程到该年级？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消添加",
    });
  } else if (confirm === "confirm") {
    const courseIdsToAdd = row != undefined ? [row.id] : dialogStatus.value.ids;

    const [err] = await to(
      addCoursesToGradeApi(currentGradeId.value, courseIdsToAdd),
    );
    if (!err) {
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      getUnbindCourseList();
      getCoreCourseList();
    }
  }
};

/**
 * 从年级移出课程
 * @param row
 */
const handleRemoveCoursesFromGrade = async (row?: CourseCourseVo) => {
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定从该年级移出选定的课程？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消移出",
    });
  } else if (confirm === "confirm") {
    const coursesToRemove = row != undefined ? [row.id] : ids.value;
    const [err] = await to(removeCoursesFromGradeApi(coursesToRemove));

    if (!err) {
      ElMessage({
        type: "success",
        message: "移出成功",
      });
      getCoreCourseList();
      dialogStatus.value.isShow = false;
    }
  }
};

/**
 * 上移课程
 * @param index
 * @param row
 */
const handleMoveCourseUp = async (index: number, row: CourseCourseVo) => {
  if (row.coreOrderNum) {
    const previousCourse = coreCourseList.value[index - 1];
    // 和上一门课交换coreOrderNum
    const temp = row.coreOrderNum;
    row.coreOrderNum = previousCourse.coreOrderNum;
    previousCourse.coreOrderNum = temp;
    sortCoreCourse();
  }
};

/**
 * 下移课程
 * @param index
 * @param row
 */
const handleMoveCourseDown = async (index: number, row: CourseCourseVo) => {
  if (row.coreOrderNum) {
    const nextCourse = coreCourseList.value[index + 1];
    // 和下一门课交换coreOrderNum
    const temp = row.coreOrderNum;
    row.coreOrderNum = nextCourse.coreOrderNum;
    nextCourse.coreOrderNum = temp;
    sortCoreCourse();
  }
};

/**
 * 保存核心课程排序
 */
const handleSaveOrderNum = async () => {
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否保存核心课程排序？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消保存",
    });
  } else if (confirm === "confirm") {
    const courseIdsToSave = coreCourseList.value
      .sort(
        (course1, course2) =>
          (course1.coreOrderNum ?? 0) - (course2.coreOrderNum ?? 0),
      )
      .map((item) => item.id ?? "")
      .filter((id) => id != "");
    const [err] = await to(
      saveCoreCourseOrderApi(currentGradeId.value, courseIdsToSave),
    );
    if (!err) {
      ElMessage({
        type: "success",
        message: "保存成功",
      });
      getCoreCourseList();
    }
  }
};

/**
 * 处理重置按钮
 */
const handleReset = async () => {
  const [err] = await to<string, string>(
    ElMessageBox.confirm("是否重置所有核心课程排序，回到初始状态?", "警告", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消重置，勾选依然是未保存状态",
    });
  } else {
    ElMessage({
      type: "success",
      message: "重置成功，恢复到加载时状态",
    });
    await getCoreCourseList();
  }
};

/**
 * 处理过滤年级
 */
const handleGradeFilter = () => {
  getGradeList();
};

/**
 * 主列表多选框选中数据
 */
const handleSelectionChange = (selection: CourseCourseVo[]) => {
  ids.value = selection.map((item) => item.id ?? "");
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/**
 * 对话框中勾选
 * @param selection
 */
const handleDialogSelectionChange = (selection: CourseCourseVo[]) => {
  dialogStatus.value.ids = selection
    .map((item: CourseLabelVo) => item.id ?? "")
    .filter((id) => id !== "");
  dialogStatus.value.selection = selection;
  dialogStatus.value.single = selection.length != 1;
  dialogStatus.value.multiple = !selection.length;

  console.log(selection);
};

/**
 * 处理关闭对话框
 */
const handleCloseDialog = () => {
  dialogStatus.value.isShow = false;
  dialogData.value = Object.assign({}, initDialogData);
  dialogStatus.value = Object.assign({}, initDialogStatus);
  unbindCourseQuery.value = Object.assign({}, initUnbindCourseQuery);
};

onMounted(() => {
  getGradeList();
});
</script>

<style scoped>
.card-header {
  display: flex;

  .text {
    width: 150px;
    /* background-color: aqua; */
  }

  .el-input {
    margin: 0 5px 0 0;
    width: 200px;
  }
}

.dialogFooter {
  margin: 20px 0 0 170px;
}
</style>
